package com.example.testsvn;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class TrangChaoActivity extends Activity {
	private ConfigDbAdapter mDbHelper;
	public static final String EXTRA_ID = null;
	public static final String EXTRA_SBN = null;
	String ID = null;
	final Context context = this;
	String Username = null;
	@Override
	public void onBackPressed() {		
		return;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trangchao);
		Intent intent1 = getIntent();
		
		 ID = intent1.getStringExtra(MainActivity.EXTRA_ID);
		if(ID == null){
			ID = intent1.getStringExtra(BinhBau.EXTRA_ID);
		}
		String ten = null;
		String bophan = null;
		int solan = 0;
		mDbHelper = new ConfigDbAdapter(this);
		mDbHelper.open();
		final Cursor c = mDbHelper.fetchNote(1);
		
		// Creating JSON Parser object
		JSONParser jParser = new JSONParser();
		// url to get all products list
		String url_xlLogin = "http://"+c.getString(c.getColumnIndexOrThrow("ServiceName"))+"/DoAnThucTap1/getNhanVien.php";

		// json success tag
		int success;

		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("ID", ID));
			JSONObject json = jParser.makeHttpRequest(url_xlLogin,
					"POST", params);
			// check your log for json response
			Log.d("getCanBo", json.toString());
			success = json.getInt("success");
			if(success == 1){
				// Nhận thông tin cán bộ
                JSONArray canboObj = json
                        .getJSONArray("canbo"); // JSON Array
             // Lấy phần tử đầu tiên 
                JSONObject canbo = canboObj.getJSONObject(0);
                ten = canbo.getString("HoTen");
                bophan = canbo.getString("BoPhan");       
                Username = canbo.getString("Username");
                solan = json.getInt("SoLan");
			}
			else{
				Intent intent = new Intent(getApplicationContext(),MainActivity.class);
				startActivity(intent);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Create the text view
		TextView textView1 = (TextView) findViewById(R.id.textView1);
		textView1.setText(ten);

		TextView textView2 = (TextView) findViewById(R.id.textView2);
		textView2.setText(bophan);

		TextView textView3 = (TextView) findViewById(R.id.textView3);
		textView3.setText("Số lần đánh giá: " + Integer.toString(solan));
		
		ImageView imgView = (ImageView) findViewById(R.id.imgCanBo);
		Drawable drawable = LoadImageFromWeb("http://24.media.tumblr.com/tumblr_ls765tOYgb1qdywcco3_400.png");
		imgView.setImageDrawable(drawable);
		
		ImageButton buttonBack = (ImageButton) findViewById(R.id.btnBack);
		buttonBack.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				// get prompts.xml view
				LayoutInflater li = LayoutInflater.from(context);
				View promptsView = li.inflate(R.layout.prompt, null);

				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);

				// set prompts.xml to alertdialog builder
				alertDialogBuilder.setView(promptsView);

				final EditText userInput = (EditText) promptsView
						.findViewById(R.id.editTextPrompt);
				final TextView txtprompt = (TextView) promptsView.findViewById(R.id.txtViewPrompt);
				txtprompt.setText("Nhập password");

				// set dialog message
				alertDialogBuilder
						.setCancelable(false)
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// Creating JSON Parser object
										JSONParser jParser = new JSONParser();
										// url to get all products list
										String url_xlLogin = "http://"+c.getString(c.getColumnIndexOrThrow("ServiceName"))+"/DoAnThucTap1/xlLogin.php";
										int success;
										
										try {
											List<NameValuePair> params = new ArrayList<NameValuePair>();
											params.add(new BasicNameValuePair("username", Username));
											params.add(new BasicNameValuePair("password", userInput.getText().toString()));
											JSONObject json = jParser.makeHttpRequest(url_xlLogin,
													"POST", params);
											// check your log for json response
											Log.d("CheckPassword", json.toString());
											success = json.getInt("success");
											if (success == 1){
												Intent intent = new Intent(getApplicationContext(),MainActivity.class);
												startActivity(intent);
											}
											else {
												dialog.cancel();
											}
											
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});

				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();

				// show it
				alertDialog.show();

			}
		});

		Button btnVote = (Button) findViewById(R.id.btnVote);
		btnVote.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// get prompts.xml view
				LayoutInflater li = LayoutInflater.from(context);
				View promptsView = li.inflate(R.layout.prompt, null);

				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);

				// set prompts.xml to alertdialog builder
				alertDialogBuilder.setView(promptsView);

				final EditText userInput = (EditText) promptsView
						.findViewById(R.id.editTextPrompt);
				userInput.setInputType(InputType.TYPE_CLASS_TEXT);
				final TextView txtprompt = (TextView) promptsView.findViewById(R.id.txtViewPrompt);
				txtprompt.setText("Nhập số biên nhận");

				// set dialog message
				alertDialogBuilder
						.setCancelable(false)
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// Creating JSON Parser object
										JSONParser jParser = new JSONParser();
										// url to get all products list
										String url_xlLogin = "http://"+c.getString(c.getColumnIndexOrThrow("ServiceName"))+"/DoAnThucTap1/checkSBN.php";
										int success;
										
										try {
											
											List<NameValuePair> params = new ArrayList<NameValuePair>();
											params.add(new BasicNameValuePair("sobiennhan", userInput.getText().toString()));
											JSONObject json = jParser.makeHttpRequest(url_xlLogin,
													"POST", params);
											// check your log for json response
											Log.d("CheckSoBienNhan", json.toString());
											success = json.getInt("success");
											if (success == 1){
												Intent intent = new Intent(getApplicationContext(),BinhBau.class);
												
												intent.putExtra(EXTRA_SBN, userInput.getText().toString());
												intent.putExtra(EXTRA_ID, ID);
												startActivity(intent);
											}
											else {
												dialog.cancel();
											}
											
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});

				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();

				// show it
				alertDialog.show();
				
			}
		});
	}
	
	private Drawable LoadImageFromWeb(String url) {
		try {
			InputStream is = (InputStream) new URL(url).getContent();
			Drawable d = Drawable.createFromStream(is, "src name");
			return d;
		} catch (Exception e) {
			System.out.println("Exc=" + e);
			return null;
		}
	}

}
